<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="380px"
    @close="onClose"
    align-center
    class="login-dialog"
  >
    <div class="dialog-content">
      <p class="subtitle">通过手机号登录或注册</p>
      
      <el-form :model="form" :rules="rules" ref="formRef" @submit.native.prevent>
        <el-form-item prop="phoneNumber">
          <el-input
            v-model="form.phoneNumber"
            placeholder="请输入手机号码"
            size="large"
          />
        </el-form-item>

        <!-- Nickname Input (for registration) -->
        <el-form-item prop="name" v-if="currentState === 'register'">
            <el-input v-model="form.name" placeholder="首次使用，请输入您的昵称" size="large" />
        </el-form-item>
      </el-form>

      <el-button
        type="primary"
        size="large"
        class="action-button"
        @click="handleAction"
        :loading="isLoading"
      >
        登录 / 注册
      </el-button>
      
      <div class="privacy-policy">
        登录/注册即表示同意 <a href="#">用户协议</a> 和 <a href="#">隐私政策</a>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import apiClient from '../axios/axios';
import { useUserStore } from '../stores/user';

const userStore = useUserStore();
const emit = defineEmits(['login-success']);

type DialogState = 'login' | 'register';

const dialogVisible = ref(false);
const currentState = ref<DialogState>('login');
const isLoading = ref(false);

const form = reactive({
  phoneNumber: '',
  name: '',
});
const formRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  phoneNumber: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' },
  ],
  name: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
});

const title = computed(() => {
  if (currentState.value === 'register') return '首次登录请完成注册';
  return '手机号登录';
});

const openDialog = () => {
  dialogVisible.value = true;
};

const onClose = () => {
  dialogVisible.value = false;
  currentState.value = 'login';
  form.phoneNumber = '';
  form.name = '';
};

const handleAction = async () => {
  const phoneFieldValid = await formRef.value?.validateField('phoneNumber').catch(() => false);
  if (!phoneFieldValid) return;

  if (currentState.value === 'register') {
      const nameFieldValid = await formRef.value?.validateField('name').catch(() => false);
      if(!nameFieldValid) return;
  }

  isLoading.value = true;
  try {
    const response = await apiClient.post('/auth/login-by-phone', form);
    const { token, user } = response.data;
    
    userStore.setCredentials(user, token);
    
    emit('login-success', user);
    ElMessage.success('操作成功！');
    onClose();

  } catch (error: any) {
    if (error.response && error.response.data.code === 'USER_NOT_FOUND') {
      ElMessage.info('该手机号尚未注册，请输入昵称以继续');
      currentState.value = 'register';
    } else {
      ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
    }
  } finally {
    isLoading.value = false;
  }
};

defineExpose({ openDialog });
</script>

<style scoped>
.login-dialog .subtitle {
  text-align: center;
  color: #606266;
  margin-bottom: 25px;
}
.action-button {
  width: 100%;
  margin-top: 10px;
}
.privacy-policy {
  margin-top: 20px;
  text-align: center;
  font-size: 12px;
  color: #909399;
}
.privacy-policy a {
  color: #409eff;
  text-decoration: none;
}
.privacy-policy a:hover {
  text-decoration: underline;
}
</style> 